const pool = require('./db');

async function initDatabase() {
    try {
        // 先删除存在的表（注意顺序：先删除有外键约束的表）
        console.log('正在删除旧表...');
        await pool.query('DROP TABLE IF EXISTS game_saves');
        await pool.query('DROP TABLE IF EXISTS users');
        console.log('旧表删除成功');

        // 创建用户表
        console.log('正在创建users表...');
        await pool.query(`
            CREATE TABLE IF NOT EXISTS users (
                id INT AUTO_INCREMENT PRIMARY KEY,
                username VARCHAR(255) UNIQUE NOT NULL,
                highest_score INT DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        `);
        console.log('users表创建成功');

        // 创建存档表
        console.log('正在创建game_saves表...');
        await pool.query(`
            CREATE TABLE IF NOT EXISTS game_saves (
                id INT AUTO_INCREMENT PRIMARY KEY,
                username VARCHAR(255) NOT NULL,
                game_state JSON NOT NULL,
                current_score INT NOT NULL,
                saved_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                is_hidden BOOLEAN DEFAULT FALSE,
                FOREIGN KEY (username) REFERENCES users(username)
            )
        `);
        console.log('game_saves表创建成功');

        // 检查并添加 is_hidden 字段
        try {
            await pool.query(`
                ALTER TABLE game_saves 
                ADD COLUMN IF NOT EXISTS is_hidden BOOLEAN DEFAULT FALSE
            `);
            console.log('is_hidden 字段添加成功');
        } catch (error) {
            console.error('添加 is_hidden 字段失败:', error);
        }

        console.log('数据库初始化完成！');
    } catch (error) {
        console.error('初始化数据库失败:', error);
    } finally {
        pool.end();
    }
}

initDatabase(); 